package com.youlai.sale.service;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.youlai.common.base.BaseServiceImpl;
import com.youlai.core.mybatisplus.handler.WrappersFactory;
import com.youlai.eng.query.BaseQuery;
import com.youlai.sale.entity.SaleItemEntity;
import com.youlai.sale.mapper.SaleItemMapper;
import com.youlai.common.model.Option;
import com.youlai.common.result.PageResult;
import com.youlai.system.model.entity.SysDict;
import com.youlai.utils.DateUtils;
import com.youlai.system.util.SecurityUtils;
import com.youlai.core.security.model.SysUserDetails;
import com.youlai.system.service.SysDictService;
import com.youlai.utils.IdWorker;
import jakarta.annotation.Resource;
import org.apache.ibatis.session.RowBounds;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class SaleItemService extends BaseServiceImpl<SaleItemMapper, SaleItemEntity> {

    @Resource
    SysDictService sysDictService;

    /**
     * 分页查询列表
     *
     * @param queryParams
     * @return
     */
    public PageResult<SaleItemEntity> queryPage(SaleItemEntity queryParams) {
        // 查询参数
        String keywords = queryParams.getKeywords();

        // 格式化为数据库日期格式，避免日期比较使用格式化函数导致索引失效
        DateUtils.toDatabaseFormat(queryParams, "startUpdateTime", "endUpdateTime");

        Integer pageSize = queryParams.getPageSize();
        if (pageSize != null) {
            int current =  queryParams.getPageNum();
            int offset = pageSize * (current-1);

            long totalCount = this.baseMapper.queryPageCount(queryParams);
            if (totalCount > 0) {
                if (offset >= totalCount) {
                    offset = offset - pageSize;
                }
                if(offset<0) {
                    offset=0;
                }
                RowBounds rowBounds = new RowBounds(offset, pageSize);
                List<SaleItemEntity> list = this.baseMapper.queryPage(queryParams,rowBounds);

                // 数据字典项
                List<SysDict> dictList = sysDictService.list(new LambdaQueryWrapper<SysDict>()
                        .eq(SysDict::getTypeCode, "currency")
                        .select(SysDict::getValue, SysDict::getName)
                );
                Map<String,String> currecyMap =  dictList.stream().collect(Collectors.toMap(SysDict::getValue,SysDict::getName));

                for(SaleItemEntity o:list) {
                     o.setCurrencyName(currecyMap.get(String.valueOf(o.getCurrency())));
                }
                //赋值
                return PageResult.success(list,totalCount);
            } else {
                return PageResult.success(new  ArrayList<SaleItemEntity>(),0);
            }
        } else {
            RowBounds rowBounds = new RowBounds(0, 1000);
            List<SaleItemEntity> list = this.baseMapper.queryPage(queryParams,rowBounds);
            return PageResult.success(list,1000l);
        }
    }

    public boolean saveOrUpdate(SaleItemEntity entity){
        boolean result = false;
        if(entity.getSaleItemId() == null) {
            // 校验该客户的货号
            Long cnt = this.count(new LambdaQueryWrapper<SaleItemEntity>()
                    .eq(SaleItemEntity::getItemNo, entity.getItemNo())
                    .eq(SaleItemEntity::getDeleted, 0)
                    .eq(SaleItemEntity::getCustomerNo, entity.getCustomerNo()));
            Assert.isTrue(cnt == 0, "该客户的货号 已经存在");

            entity.setSaleItemId(IdWorker.generateId());
            SysUserDetails user = SecurityUtils.getUser();
            entity.setCreateBy(user.getUserId());
            entity.setCreateName(user.getUsername());
            entity.setUpdateBy(user.getUserId());
            entity.setUpdateName(user.getUsername());
            result = this.save(entity);
        } else {
            Long id = entity.getSaleItemId();
            // 校验该客户的货号
            Long cnt = this.count(new LambdaQueryWrapper<SaleItemEntity>()
                    .ne(SaleItemEntity::getSaleItemId, id)
                    .eq(SaleItemEntity::getItemNo, entity.getItemNo())
                    .eq(SaleItemEntity::getDeleted, 0)
                    .eq(SaleItemEntity::getCustomerNo, entity.getCustomerNo()));
            Assert.isTrue(cnt == 0, "该客户的货号 已经存在");
            result = this.update(WrappersFactory.updateWithNullField(entity).eq(SaleItemEntity::getSaleItemId,id));
        }
        return result;
    }

    public SaleItemEntity findById(Long id){
        SaleItemEntity entity = this.getOne(new LambdaQueryWrapper<SaleItemEntity>()
                .eq(SaleItemEntity::getSaleItemId, id));
        Assert.isTrue(entity != null, "数据项不存在");
        return entity;
    }


    public List<SaleItemEntity> findListBy(SaleItemEntity entity){
//        List<SaleItemEntity> list =  this.baseMapper.selectJoinList(SaleItemEntity.class, new MPJLambdaWrapper<SaleItemEntity>()
//                .selectAll(SysOrgEntity.class)
//                .selectAs(SysUser::getUsername, SysOrgEntity::getUpdateName)
//                .leftJoin(SysUser.class, SysUser::getId, SysOrgEntity::getUpdateBy)
//                .eq(entity.getSaleItemId()!=null, SaleItemEntity::getSaleItemId, entity.getSaleItemId())
//                .eq(StringUtils.isNotEmpty(entity.getItemNo()),SaleItemEntity::getItemNo, entity.getItemNo())
//                .orderByDesc(SysOrgEntity::getUpdateTime));
        List<SaleItemEntity> list = baseMapper.queryList(entity);
        return list;
    }

    public Boolean deleteAllById(String idStrs){
//        SysUserDetails user = SecurityUtils.getUser();
        Assert.isTrue(StrUtil.isNotBlank(idStrs), "删除数据为空");
        //
        List<Long> ids = Arrays.asList(idStrs.split(","))
                .stream()
                .map(id -> Long.parseLong(id))
                .collect(Collectors.toList());

        boolean result = this.removeByIds(ids); //因为配置了 logic-delete-field: deleted 这里是逻辑删除
        //this.baseMapper.deleteBatchIds(ids); //这里是物理删除
        return result;
    }

    public List<Option> listEngEmpOptions(BaseQuery baseQuery) {
        SaleItemEntity entity = new SaleItemEntity();
        entity.setDeleted(0);
        entity.setStatus(1);
        entity.setCustomerName(baseQuery.getCustomerName());
        List<SaleItemEntity> list = baseMapper.queryList(entity);
        List<Option> lastList = new ArrayList<>();
        for(SaleItemEntity o:list) {
            Option option = new Option<String>();
            option.setLabel(o.getItemNo());
            option.setValue(o.getCustomerNo());
            lastList.add(option);
        }
        return lastList;
    }
}


